const gulp = require('gulp');
const ts = require('gulp-typescript');
const cls = require("gulp-clean")
const uglify = require('gulp-uglify-es').default
const es = require('event-stream')
const filter = require('gulp-filter')
const tsProject = ts.createProject('tsconfig.json');

function clean(cb) {
    return gulp.src("./dist/*.*", { allowEmpty: true })
        .pipe(cls());
}

function compile() {
    let tsResult = tsProject.src()
        .pipe(tsProject());
    return es.merge(
        tsResult.dts,
        tsResult.js.pipe(filter(["**/scada.js"])).pipe(uglify({ compress: true }))
    ).pipe(gulp.dest('./dist'));
};
function cssfile() {
    return gulp.src(["./src/style.css", "./README.md"])
        .pipe(gulp.dest('./dist'))
}
function packageFile(cb) {
    return es.merge(
        gulp.src("./package.json")
            .pipe(es.through(function (data) {
                let json = JSON.parse(data.contents.toString());
                delete json.scripts;
                delete json.devDependencies;
                delete json.dependencies;
                data.contents = Buffer.from(JSON.stringify(json, null, '  '));
                this.emit('data', data);
            })),
        gulp.src("./src/style.css")
    ).pipe(gulp.dest('./dist'))
}
function compile_dev(cb) {
    return tsProject.src()
        .pipe(tsProject())
        .pipe(filter(["**", "!**/global.js"]))
        .pipe(gulp.dest('./dist'));
}
function watch_dev(cb) {
    gulp.watch("./src/*.ts", gulp.series(compile_dev));
}
function watch_Final(cb) {
    gulp.watch("./src/*.ts", gulp.series(compile));
}

exports.build = gulp.series(clean, gulp.parallel(cssfile, packageFile, compile));
exports.default = this.build;
exports.watch = gulp.series(clean, gulp.parallel(cssfile, packageFile, compile_dev), watch_dev);
exports.watchFinal = gulp.series(clean, gulp.parallel(cssfile, packageFile, compile), watch_Final);
